import requests
import schedule
import time
import json
import logging
from datetime import datetime
import os

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('watch_request.log'),
        logging.StreamHandler()
    ]
)

class RequestWatcher:
    def __init__(self, url, method='GET', headers=None, data=None, interval=60):
        """
        初始化请求监视器
        :param url: 请求的URL
        :param method: 请求方法 (GET, POST, etc.)
        :param headers: 请求头
        :param data: 请求数据
        :param interval: 请求间隔（秒）
        """
        self.url = url
        self.method = method.upper()
        self.headers = headers or {}
        self.data = data
        self.interval = interval
        self.session = requests.Session()

    def make_request(self):
        """
        发送请求并记录结果
        """
        try:
            start_time = datetime.now()
            logging.info(f"开始发送请求: {self.url}")

            # 发送请求
            if self.method == 'GET':
                response = self.session.get(self.url, headers=self.headers)
            elif self.method == 'POST':
                response = self.session.post(self.url, headers=self.headers, json=self.data)
            else:
                raise ValueError(f"不支持的请求方法: {self.method}")

            # 计算请求时间
            end_time = datetime.now()
            duration = (end_time - start_time).total_seconds()

            # 记录响应
            logging.info(f"请求完成 - 状态码: {response.status_code}")
            logging.info(f"响应时间: {duration:.2f}秒")
            
            # 尝试解析JSON响应
            try:
                response_data = response.json()
                logging.info(f"响应数据: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
            except json.JSONDecodeError:
                logging.info(f"响应内容: {response.text[:200]}...")  # 只记录前200个字符

            # 检查响应状态
            if response.status_code != 200:
                logging.warning(f"请求返回非200状态码: {response.status_code}")

        except requests.RequestException as e:
            logging.error(f"请求发生错误: {str(e)}")
        except Exception as e:
            logging.error(f"发生未知错误: {str(e)}")

    def start(self):
        """
        启动定时请求
        """
        logging.info(f"启动请求监视器 - URL: {self.url}, 间隔: {self.interval}秒")
        
        # 立即执行一次
        self.make_request()
        
        # 设置定时任务
        schedule.every(self.interval).seconds.do(self.make_request)
        
        # 保持脚本运行
        while True:
            try:
                schedule.run_pending()
                time.sleep(1)
            except KeyboardInterrupt:
                logging.info("收到停止信号，正在退出...")
                break
            except Exception as e:
                logging.error(f"运行出错: {str(e)}")
                time.sleep(5)  # 出错后等待5秒再继续

def main():
    # 配置请求参数
    url = "http://127.0.0.1:8010/run_link"  # 替换为你的API地址
    headers = {
        "Content-Type": "application/json",
        # "Authorization": "Bearer your-token"  # 如果需要认证
    }
    data = {
        "key": "value"  # 请求数据
    }
    
    # 创建请求监视器实例
    watcher = RequestWatcher(
        url=url,
        method="GET",  # 或 "GET"
        headers=headers,
        data=data,
        interval=60 * 10  # 每60秒发送一次请求
    )
    
    # 启动监视器
    watcher.start()

main()